package com.sgb.kjwl.view.ui.activity.enterprise;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.google.gson.Gson;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddDealedCasesBinding;
import com.sgb.kjwl.di.enterprise.DaggerEnterpriseComponent;
import com.sgb.kjwl.di.enterprise.EnterpriseModule;
import com.sgb.kjwl.model.entity.enterprise.TransactionCasesEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.enterprise.PublishAddDealedCasesActivityModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.InputFilterUtils;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * Time:2021/4/16
 * Author:黄淋
 * Description:发布服务-成交案例
 */
public class PublishAddDealedCasesActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    ActivityAddDealedCasesBinding mBinding;

    @Inject
    PublishAddDealedCasesActivityModel mModel;
    Map<String, Object> mMap;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private Thread thread;
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private boolean isLoaded = false;
    private String mProvinceNo;//省No
    private String mCityNo;//市No
    private String mAreaNameNo;//区No
    String province;//省
    String city;//市
    String areaName;//区
    String id;
    TransactionCasesEntity mEntity;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseComponent.builder()
                .appComponent(appComponent)
                .enterpriseModule(new EnterpriseModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_dealed_cases);

        mBinding.itvServiceCity.setOnWholeItemClickListener(this);
        mBinding.tvUpload.setOnClickListener(this);
        mBinding.llYiwancheng.setOnClickListener(this);
        mBinding.llBanlizhong.setOnClickListener(this);
        InputFilterUtils.setEditTextInhibitInputSpaChat(mBinding.itvServiceName.getContent_edt(), 30);
        InputFilterUtils.setEditTextInhibitInputSpaChat(mBinding.itvServiceCustomer.getContent_edt(), 15);
    }

    @Override
    protected void init() {
        mMap = new HashMap<>();
        mEntity = (TransactionCasesEntity) getIntent().getSerializableExtra(RouterKey.DATA);
        if (mEntity != null) {
            mMap.put("serviceId", mEntity.getServiceId());
            mMap.put("id", mEntity.getId());
            mBinding.itvServiceName.setContent(mEntity.getTransactionServiceName());
            mBinding.itvServiceCustomer.setContent(mEntity.getServeCustomers());
            String provinceCode = mEntity.getProvincesCode();
            Gson gson = new Gson();
            TransactionCasesEntity.ProvinceCode provinceCodeEntity = gson.fromJson(provinceCode, TransactionCasesEntity.ProvinceCode.class);
            mBinding.itvServiceCity.setContent(provinceCodeEntity.getProvinceName() + provinceCodeEntity.getCityName() + provinceCodeEntity.getAreaName());
            mBinding.ivYiwancheng.setSelected(mEntity.getServiceStatus() == 0);
            mBinding.ivBanlizhong.setSelected(mEntity.getServiceStatus() == -1);
        }
        id = getIntent().getStringExtra("id");
        if (id != null && !id.equals("")) {
            mMap.put("serviceId", id);
        }
        mModel.ldServiceCity.observe(this, this::showAddressPop);
        mModel.ldSaveSuccess.observe(this, a -> addSuccess());
        mModel.ldUpdateSuccess.observe(this, a -> addSuccess());
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_upload://提交
                if (!ClickUtils.isDoubleClick()) {
                    // TODO: 2021/4/16 上传
                    checkData();
                }
                break;
            case R.id.ll_yiwancheng://已完成
                if (!mBinding.ivYiwancheng.isSelected()) {
                    mBinding.ivYiwancheng.setSelected(true);
                }
                mBinding.ivBanlizhong.setSelected(false);
                break;
            case R.id.ll_banlizhong://处理中
                if (!mBinding.ivBanlizhong.isSelected()) {
                    mBinding.ivBanlizhong.setSelected(true);
                }
                mBinding.ivYiwancheng.setSelected(false);
                break;
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_service_city://选择服务城市
                if (!ClickUtils.isDoubleClick()) {
                    if (addressEntityList != null) {
                        showCityPop("选择城市");
                    } else {
                        mModel.getAddressModel(PublishAddDealedCasesActivity.this);
                    }
                }
                break;
        }
    }

    private void checkData() {
        if (TextUtils.isEmpty(mBinding.itvServiceName.getContent().trim())) {
            MToast.showToast(PublishAddDealedCasesActivity.this, "请输入服务名称！");
            return;
        } else if (TextUtils.isEmpty(mBinding.itvServiceCustomer.getContent().trim())) {
            MToast.showToast(PublishAddDealedCasesActivity.this, "请输入联系人姓名！");
            return;
        } else if (TextUtils.isEmpty(mBinding.itvServiceCity.getContent().trim())) {
            MToast.showToast(PublishAddDealedCasesActivity.this, "请选择服务城市！");
            return;
        } else if (!mBinding.ivYiwancheng.isSelected() && !mBinding.ivBanlizhong.isSelected()) {
            MToast.showToast(PublishAddDealedCasesActivity.this, "请选择服务状态！");
            return;
        }
        TransactionCasesEntity.ProvinceCode entity = new TransactionCasesEntity.ProvinceCode();
        entity.setProvinceId(mProvinceNo);
        entity.setProvinceName(province);
        entity.setCityId(mCityNo);
        entity.setCityName(city);
        entity.setAreaId(mAreaNameNo);
        entity.setAreaName(areaName);
        if (mProvinceNo != null && !mProvinceNo.equals("")) {
            Gson gson = new Gson();
            mMap.put("provincesCode", gson.toJson(entity));
        } else if (mEntity != null) {
            mMap.put("provincesCode", mEntity.getProvincesCode());
        }
        mMap.put("transactionServiceName", mBinding.itvServiceName.getContent().trim());
        mMap.put("serveCustomers", mBinding.itvServiceCustomer.getContent().trim());
        mMap.put("serviceStatus", mBinding.ivYiwancheng.isSelected() ? 0 : -1);
        // TODO: 2021/4/19 上传
        if (mEntity != null) {
            mModel.updateTransactionCases(this, mMap);
        } else {
            mModel.saveTransactionCases(this, mMap);
        }
    }

    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop("选择城市");
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop("选择城市");
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    /**
     * 选择服务城市 单选
     *
     * @param title 弹窗标题
     */
    private void showCityPop(String title) {
        CityPickView cityOption = new CityPickBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    province = addressEntityList.get(options1).getName();
                    city = opt2.get(options1).get(options2).getName();
                    areaName = "";
                    mProvinceNo = addressEntityList.get(options1).getNo();
                    mCityNo = opt2.get(options1).get(options2).getNo();
                    mAreaNameNo = "";
                    cityPosition3 = options3;
                    cityPosition2 = options2;
                    cityPosition1 = options1;
                    StringBuilder builder = new StringBuilder();
                    builder.append(province);
                    if (!TextUtils.isEmpty(city)) {
                        builder.append("-").append(city);
                    }
                    if (!TextUtils.isEmpty(areaName)) {
                        builder.append("-").append(areaName);
                    }
                    mBinding.itvServiceCity.setContent(builder.toString());
                } else {
                    province = addressEntityList.get(options1).getName();
                    city = opt2.get(options1).get(options2).getName();
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    mProvinceNo = addressEntityList.get(options1).getNo();
                    mCityNo = opt2.get(options1).get(options2).getNo();
                    mAreaNameNo = opt3.get(options1).get(options2).get(options3).getNo();
                    cityPosition3 = options3;
                    cityPosition2 = options2;
                    cityPosition1 = options1;
                    StringBuilder builder = new StringBuilder();
                    builder.append(province);
                    if (!TextUtils.isEmpty(city)) {
                        builder.append("-").append(city);
                    }
                    if (!TextUtils.isEmpty(areaName)) {
                        builder.append("-").append(areaName);
                    }
                    mBinding.itvServiceCity.setContent(builder.toString());
                }
            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    /**
     * 添加成功
     */
    public void addSuccess() {
        ActivityJump.jumpToActivity(PublishAddDealedCasesActivity.this, PublishServiceDealedCasesActivity.class);
    }
}
